package com.dx.mes.web.common.authorization.manager.impl;

import com.dx.mes.common.core.redis.RedisManager;
import com.dx.mes.web.common.authorization.manager.TokenManager;
import com.dx.mes.web.common.authorization.model.TokenModel;
import com.dx.mes.web.common.config.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * 通过Redis存储和验证token的实现类
 * @see com.scienjus.authorization.manager.TokenManager
 * @author ScienJus
 * @date 2015/7/31.
 */
@Component
public class RedisTokenManager implements TokenManager {

//    private RedisTemplate<Long, String> redis;
    @Resource
    private RedisManager redisManager;

//    @Autowired
//    public void setRedis(RedisTemplate redis) {
//        this.redis = redis;
//        //泛型设置成Long后必须更改对应的序列化方案
//        redis.setKeySerializer(new JdkSerializationRedisSerializer());
//    }

    public TokenModel createToken(String userId) {
        Jedis jedis = redisManager.getJedis();
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenModel model = new TokenModel(userId, token);
        //存储到redis并设置过期时间
        jedis.setex(userId, Constants.TOKEN_EXPIRES_HOUR * 60 * 60 , token);
        redisManager.returnResource(jedis);//释放redis实例
//        redis.boundValueOps(userId).set(token, Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return model;
    }

    public TokenModel getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        String userId = param[0];
        String token = param[1];
        return new TokenModel(userId, token);
    }

    public boolean checkToken(TokenModel model) {
        Jedis jedis = redisManager.getJedis();
        if (model == null) {
            return false;
        }
        byte[] bs = jedis.get(model.getUserId().getBytes());
        String token = "";
        if (bs != null) {
            token = new String(bs);
        }
//        String token = redis.boundValueOps(model.getUserId()).get();
        if (StringUtils.isEmpty(token) || !token.equals(model.getToken())) {
            return false;
        }
        //todo 如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        jedis.setex(model.getUserId(), Constants.TOKEN_EXPIRES_HOUR * 60 * 60 , token);
        redisManager.returnResource(jedis);//释放redis实例
//        redis.boundValueOps(model.getUserId()).expire(Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return true;
    }

    public void deleteToken(String userId) {
        Jedis jedis = redisManager.getJedis();
        jedis.del(userId);
        redisManager.returnResource(jedis);//释放redis实例
//        jedis.delete(userId);
    }
}
